<?php
	class DataHandle{

		//Time Filter time paramerats processing
		private $request ;
		private $format ;

		public function setRequest($req){
			$this->request = $req;
		}
		public function setFormat($fmr){
			$this->format = $fmr;
		}
		public function processTime(&$startTime, &$endTime){
			$timeHandle = new TimeHandle();

			$timeFrame = getValue($_GET['timeFrame']);

			//If its the case that time context is not specified
			//period is defaulth
			if ($timeFrame == "")
					$timeFrame = "period";

			//If its the case that year is selected
			//startTime will be 1. jan of the selected year
			//endTime will be 1. Jan of next Year	
			if($timeFrame == "year"){

				$yYear = getValue($_GET['yYear']);
				if ($yYear != ""){
					$timeHandle->getYear($yYear, $startTime, $endTime);
				}
			}
			//If its the case that month is selected year also has to be specified
			//startTime will be 1. selected Month and selected year
			//endTime will be 1. of the following Month and selected year
			else if($timeFrame == "month"){

				$mMonth = getValue($_GET['mMonth']);
				$mYear = getValue($_GET['mYear']);

				if($mYear != "" and $mMonth != ""){
					$timeHandle->getMonth($mMonth, $mYear, $startTime, $endTime);
				}
			}
			//If its the case that period is selected
			//startTime will be selected start date
			//endTime will be selected end date
			//If one day is selected period will be between 
			//selected and following day
			else if ($timeFrame == "period"){

				$pStart = getValue($_GET['pStart']);
				$pEnd 	= getValue($_GET['pEnd']);
				$pOneDay= getValue($_GET['pOneDay']);

				if ($pStart != ""){

					$startTime = $pStart;
					if($pOneDay == "oneDay"){
						$timeHandle->getDay($pStart, $startTime, $endTime);
					}
					else if($pEnd != "")
						$endTime = $pEnd;

				}
			}
			else{
				$temp = array();
				$temp['error'] = $this->request.": Bad request";
				return json_encode($temp);
			}

			if(date_create($startTime) >= date_create($endTime)){
				$temp = array();
				$temp['error'] = $this->request." Start time is greater or equal than end time";
				return json_encode($temp);
			}
		}
		//Time Filter filter paramerats processing
		public function processFilters(&$startTime, &$endTime, $filterTimeTable, $filterTimeField){
		
			$line 		= getValue($_GET['line']);
			$shift 		= getValue($_GET['shift']);

			$filterQuery = "
				WHERE ".$filterTimeTable.".".$filterTimeField." >= convert(datetime,'".$startTime."',104) AND 
				".$filterTimeTable.".".$filterTimeField." <= convert(datetime,'".$endTime."',104)";

			if ($line == "")
				$line = "All";

			if ($line != "All" )
				$filterQuery = $filterQuery." AND ".$filterTimeTable.".line_id=".$line." ";

			if ($shift == "")
				$shift = "All";

			if ($shift != "All" )
				$filterQuery = $filterQuery." AND ".$filterTimeTable.".shift=".$shift." ";

			return $filterQuery;
		}



		public function printJSON(&$sql, &$queryString){
		
			//preform sql query
			$result = $sql->query($queryString);
			$timeHandle = new TimeHandle();

			if($result != null){
				//var_dump($result);

				$jsonArray = array();


				//For each row
				foreach ($result as $row) {
					$temp = array();

					//For each row we extract array keys and values
					//and colomn count
					$i = count($row);
					$keys 	= array_keys($row);
					//var_dump($keys);
					$values = array_values($row);
					//var_dump($values);

					//now we go trought each column
					if($keys != NULL){
						for($a = 0; $a < $i; $a++) {							
							//we filter array results which doesnt have 
							//numbers for keys and store results in to
							//the temp array
							if($a !== $keys[$a] && $a/2 !== $keys[$a]){

								if($this->format !== null && $this->format[$keys[$a]] !== null){

									$formatType  = substr($this->format[$keys[$a]], 0,4);
									$formatValue = substr($this->format[$keys[$a]], 4);

									if($formatType == "numb"){
										$temp[$keys[$a]] = 
											formatNumber(
												getValue($row[$keys[$a]]),
												$formatValue
												);
									}
									else if($formatType == "date"){
										$temp[$keys[$a]] = 
											$timeHandle->formatTime( 
												getValue( $row[$keys[$a]] ),
												$formatValue
										);
									}
								}
								else{
									$temp[$keys[$a]] = getValue($row[$keys[$a]]);
								}
							}
						}
					}
					//generated temp array is then stored in to
					//json array 
					array_push($jsonArray, $temp);
				}
				$json = json_encode($jsonArray, JSON_UNESCAPED_SLASHES);
			}
			else{
				$temp = array();
				$temp['error'] = $this->request.": No results";
				print json_encode($temp);
			}
			unset($timeHandle);
			return $json;
		}
		public 	function printCSV(&$sql, &$queryString){
			$result = $sql->query($queryString);
			$timeHandle = new TimeHandle();

			if($result != null){

				
				header("Content-Disposition: attachment; filename=PackagingExport.csv");
				header("Content-type: application/csv; charset=UTF-8");
				header('Expires: 0');
				header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
				header('Pragma: public');
				

				$output = fopen('php://output', 'w');

				$row = $result[0];
				
				$csv = array();

				//For each row we extract array keys and values
				//and colomn count
				$i 		= count($row);
				$keys 	= array_keys($row);

				//now we go trought each column

				for($a = 0; $a < $i; $a++) {
					
					//we filter array results which doesnt have 
					//numbers for keys and store results in to
					//the temp array
					if($a !== $keys[$a] && $a/2 !== $keys[$a]){
						array_push($csv, $keys[$a]);
					}
				}

				fputcsv($output, $csv, ",");

				//For each row
				foreach ($result as $row) {
					$csv = array();
					
					//For each row we extract array keys and values
					//and colomn count
					$i = count($row);
					$keys 	= array_keys($row);
					//var_dump($keys);
					$values = array_values($row);
					//var_dump($values);

					//now we go trought each column
					if($keys != NULL){
						for($a = 0; $a < $i; $a++) {							
							//we filter array results which doesnt have 
							//numbers for keys and store results in to
							//the temp array
							if($a !== $keys[$a] && $a/2 !== $keys[$a]){

								if($this->format !== null && $this->format[$keys[$a]] !== null){

									$formatType  = substr($this->format[$keys[$a]], 0,4);
									$formatValue = substr($this->format[$keys[$a]], 4);

									if($formatType == "numb"){
										array_push($csv, 
											formatNumber(
												getValue($row[$keys[$a]]),
												$formatValue
												)
										);
									}
									else if($formatType == "date"){
										array_push($csv, 
											$timeHandle->formatTime( 
												getValue( $row[$keys[$a]] ),
												$formatValue
												)
										);
									}
								}
								else{
									array_push($csv, getValue($row[$keys[$a]]));
								}
							}
						}
					}

					//generated temp array is then stored in to
					//json array 
					//var_dump($csv);
					fputcsv($output, $csv, ",");
				}
				fclose($output);
			}
			else{
				$temp = array();
				$temp['error'] = $this->request.": No results";
				print json_encode($temp);
			}
		}



		public function addItemsQuery(&$sql, $get, $tableName){
			$first = true;
			$keyString = "
				INSERT INTO ".$tableName." (";
			$valueString = "VALUES (";
			
			foreach($get as $key => $value){
				if($key != "action" && $key != "request"){
					if($key == "default")
						$key = "[default]";

					if($first == true){
						$keyString = $keyString.$key;
						$valueString = $valueString."'".$value."'";
						$first = false;
					}
					else{
						$keyString = $keyString.",".$key;
						$valueString = $valueString.","."'".$value."'";
					}
				}
			}

			$keyString = $keyString.")";
			$valueString = $valueString.")";

			$queryString = $keyString.$valueString;
			echo $queryString;
			$sql->query($queryString);
		}
		public function updateItemsQuery(&$sql, $get, $tableName){
			$firstKey = true;
			$firstValue = true;
			$queryString = "UPDATE ".$tableName;
			$keyString = " WHERE ";
			$valueString = " SET ";

			foreach($get as $key => $value){
				if($key != "action" && $key != "request"){
					if(substr($key,0,5) == "find_"){
						$tempKey = substr($key,5);
						
						if($tempKey == "default")
							$tempKey = "[default]";


						if($firstKey == true){
							$keyString = $keyString.$tempKey."="."'".$value."'";
							$firstKey = false;
						}
						else{
							$keyString = $keyString." AND ".$tempKey."="."'".$value."'";
						}
					}
					else{
						if($key == "default")
							$key = "[default]";

						if($firstValue == true){
							$valueString = $valueString.$key."="."'".$value."'";
							$firstValue = false;
						}
						else{
							$valueString = $valueString.",".$key."="."'".$value."'";
						}

					}
				}
			}
			$queryString = $queryString.$valueString.$keyString;
			echo $queryString;
			$sql->query($queryString);
		}
		public function deleteItemsQuery(&$sql, $get, $tableName){
			$first = true;
			$queryString = "
				DELETE FROM ".$tableName." WHERE ";

			foreach($get as $key => $value){
				if($key != "action" && $key != "request"){
					if($key == "default")
						$key = "[default]";

					if($first == true){
						$queryString = $queryString.$key."="."'".$value."'";
						$first = false;
					}
					else{
						$queryString = $queryString." AND ".$key."="."'".$value."'";
					}
				}
			}
			echo $queryString;
			$sql->query($queryString);
		}
	}
?>